package com.any.hook.core.webapi.util;

import com.any.hook.common.exception.HookException;
import com.any.hook.core.Engine;
import com.any.hook.core.webapi.config.WebApiErrorCode;
import com.any.hook.core.webapi.service.EtlJobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class JobTask implements Runnable {
    private static final Logger LOG = LoggerFactory
            .getLogger(JobTask.class);
    private String context;
    private Long jobid;
    private EtlJobService etlJobService;

    public JobTask(String context, Long jobid, EtlJobService etlJobService) {
        this.context = context;
        this.jobid = jobid;
        this.etlJobService = etlJobService;
    }

    public String getContext() {
        return context;
    }

    public void setContext(String context) {
        this.context = context;
    }

    public Long getJobid() {
        return jobid;
    }

    public void setJobid(Long jobid) {
        this.jobid = jobid;
    }

    @Override
    public void run() {
        try {
            Engine.hookApi(this.context, this.jobid);
            if(etlJobService.changeJobStat(this.jobid,JobStat.JOB_STOP)!=1){
                throw HookException.asHookException(WebApiErrorCode.API_RUNTIME_ERROR,
                        String.format("请联系开发人员，数据库中找不到任务:%s .",jobid));
            }
        }catch (Exception e){
            String message;
            if(e instanceof HookException){
                message=ExceptionTracker.trace(e);
            }else {
                message=ExceptionTracker.trace(HookException.asHookException(WebApiErrorCode.API_RUNTIME_ERROR,e.getCause()));
            }
            LOG.error(message);
        }

    }
}
